package com.example.fcm;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import java.io.IOException;
import java.io.InputStream;

public class FCMServer {

    public static void main(String[] args) {
        try {
            // 初始化 Firebase Admin SDK
            initializeFirebase();

            // 要发送的目标设备 Token 从android端FirebaseMessaging.getInstance().getToken()获取
            //String targetToken = "YOUR_DEVICE_FCM_TOKEN";
            String targetToken = "dtFTrtMqTIKYVuZi6AcOHP:APA91bFpwIjpBngThcn_8Qa7MAKyVCbk0LJKgXz1ASZzuyujTl7OjBlCurtrBxRdF3h4lifFDTfUHnkGJ8JbfHPXWx1c94cn1-r0CBYSgWZrEglBneb62Ng";

            // 构建消息
            Message message = Message.builder()
                    .setToken(targetToken)
                    .setNotification(Notification.builder()
                            .setTitle("Hello from FCM")
                            .setBody("This is a test notification.")
                            .build())
                    .putData("key1", "value1") // 可选：添加自定义数据
                    .putData("key2", "value2")
                    .build();

            // 发送消息
            String response = FirebaseMessaging.getInstance().send(message);

            // 打印响应
            System.out.println("Successfully sent message: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化 Firebase Admin SDK
     */
    private static void initializeFirebase() throws IOException {
        // 指定服务账号密钥的路径
        //FileInputStream serviceAccount = new FileInputStream("config/service-account.json"); //放在 config 目录下
        InputStream serviceAccount = FCMServer.class.getClassLoader().getResourceAsStream("service-account.json"); //放在 resources 目录下

        // 配置 FirebaseOptions
        FirebaseOptions options = FirebaseOptions.builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .build();

        // 初始化 FirebaseApp
        FirebaseApp.initializeApp(options);
    }
}
